package br.com.foxline.atlasmobile.handler;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import br.com.foxline.atlasmobile.R;
import br.com.foxline.atlasmobile.dao.ImovelDao;
import br.com.foxline.atlasmobile.entities.Annex;
import br.com.foxline.atlasmobile.entities.Imovel;

public class CaptureActivity extends Activity {

	private ImovelDao imovelDao;
	private Imovel imovel;
	private static final String IMOVEL = "getimovel";

	private String ALBUMNAME = "atlasmobile";

	private static String PASTE_NAME = "";

	private static final int CAPTURAR_IMAGEM = 100;

	private static final String JPEG_FILE_PREFIX = "IMG_";
	private static final String JPEG_FILE_SUFFIX = ".jpg";
	private static final String ANNEX = "annex";

	private Annex annex;

	private Uri uri;

	private String mCurrentPhotoPath;
	private File file = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_capture);
		imovelDao = new ImovelDao(getApplicationContext());
		
		if (getIntent().getSerializableExtra(IMOVEL) != null) {
			imovel = (Imovel) getIntent().getSerializableExtra(IMOVEL);
		} else {
			imovel = new Imovel();
		}

		PASTE_NAME = File.separator + "imovel-"+imovel.getId();

		capturarImagem(findViewById(R.id.imageView1));

	}

	public void capturarImagem(View v) {
		if (isIntentAvailable(this, MediaStore.ACTION_IMAGE_CAPTURE)) {
			dispatchTakePictureIntent(100);
		}
	}

	private File createImageFile() throws IOException {

		Date date = new Date();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
				"yyyyMMdd_HHmmss");

		String timeStamp = simpleDateFormat.format(date);
		String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
		File albumF = getAlbumDir();
		File imageF = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX,
				albumF);

		annex = new Annex();
		annex.setCreate_at(date);
		annex.setName(imageF.getName());
		annex.setType(JPEG_FILE_SUFFIX);

		return imageF;
	}

	public File getAlbumStorageDir() {
		File file = new File(
				Environment
						.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
						+ "/" + ALBUMNAME + "/" + PASTE_NAME + "/");

		return file;
	}

	private File getAlbumDir() {
		File storageDir = null;

		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {

			storageDir = getAlbumStorageDir();

			if (storageDir != null) {
				if (!storageDir.mkdirs()) {
					if (!storageDir.exists()) {
						Log.d("CameraSample", "failed to create directory");
						return null;
					}
				}
			}

		} else {
			Log.v(getString(R.string.app_name),
					"External storage is not mounted READ/WRITE.");
		}

		return storageDir;
	}

	private void dispatchTakePictureIntent(int actionCode) {
		Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

		try {
			file = setUpPhotoFile();
			mCurrentPhotoPath = file.getAbsolutePath();
			uri = Uri.fromFile(file);
			takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
		} catch (IOException e) {
			e.printStackTrace();
			file = null;
			mCurrentPhotoPath = null;
		}
		startActivityForResult(takePictureIntent, actionCode);
	}

	private File setUpPhotoFile() throws IOException {

		File f = createImageFile();
		mCurrentPhotoPath = f.getAbsolutePath();

		return f;
	}

	private void galleryAddPic() {
		Intent mediaScanIntent = new Intent(
				"android.intent.action.MEDIA_SCANNER_SCAN_FILE");
		File f = new File(mCurrentPhotoPath);
		mediaScanIntent.setData(uri);
		this.sendBroadcast(mediaScanIntent);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == CAPTURAR_IMAGEM) {
			if (resultCode == RESULT_OK) {
				mostrarMensagem("Imagem capturada!");
				galleryAddPic();

				Intent intent = new Intent();
				annex.setUri(uri.toString());

				intent.putExtra(ANNEX, annex);
				setResult(RESULT_OK, intent);
				finish();
			} else {
				mostrarMensagem("Imagem não capturada!");
				file.delete();
				finish();
			}
		}
	}

	private void mostrarMensagem(String msg) {
		Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
	}

	/**
	 * Indicates whether the specified action can be used as an intent. This
	 * method queries the package manager for installed packages that can
	 * respond to an intent with the specified action. If no suitable package is
	 * found, this method returns false.
	 * http://android-developers.blogspot.com/2009/01/can-i-use-this-intent.html
	 * 
	 * @param context
	 *            The application's environment.
	 * @param action
	 *            The Intent action to check for availability.
	 * 
	 * @return True if an Intent with the specified action can be sent and
	 *         responded to, false otherwise.
	 */
	public static boolean isIntentAvailable(Context context, String action) {
		final PackageManager packageManager = context.getPackageManager();
		final Intent intent = new Intent(action);
		List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
				PackageManager.MATCH_DEFAULT_ONLY);
		return list.size() > 0;
	}

}
